@page "/exams/generate"
@inject ILocalStorageService LocalStorage
@inject IExamService ExamService
@inject ILogService LogService
@inject NavigationManager Navigation

<PageTitle>生成试卷</PageTitle>

<div>
    <Title Level="2">生成试卷</Title>
    <Text Type="secondary">基于AI技术，为孩子生成个性化练习题</Text>
    
    <Card Style="margin-top: 24px;">
        <Form Model="request" 
              LabelCol="new ColLayoutParam { Span = 4 }" 
              WrapperCol="new ColLayoutParam { Span = 20 }"
              OnFinish="GenerateExam">
            
            <FormItem Label="选择孩子" Required>
                <Select @bind-Value="request.ChildId" 
                        Placeholder="请选择孩子"
                        OnChange="OnChildChanged"
                        TItemValue="int"
                        TItem="int">
                    <SelectOptions>
                        @if (children?.Any() == true)
                        {
                            @foreach (var child in children)
                            {
                                <SelectOption Value="child.Id" Label="@($"{child.Name} ({child.Grade}年级 {child.Semester} {child.Stage})")" TItemValue="int" TItem="int" />
                            }
                        }
                    </SelectOptions>
                </Select>
                @if (children?.Any() != true)
                {
                    <div style="margin-top: 8px;">
                        <Alert Type="@AlertType.Warning" 
                               Message="请先添加孩子档案" />
                    </div>
                }
            </FormItem>
            
            <FormItem Label="试卷类型" Required>
                <RadioGroup @bind-Value="request.ExamType" @bind-Value:after="OnExamTypeChangedAsync">
                    @foreach (var type in ExamTypes.GetAll())
                    {
                        <Radio Value="type">@type</Radio>
                    }
                </RadioGroup>
                @if (!string.IsNullOrEmpty(examTypeDescription))
                {
                    <div style="margin-top: 8px; color: #666; font-size: 14px;">
                        @examTypeDescription
                    </div>
                }
            </FormItem>
            
            <FormItem Label="难度等级">
                <RadioGroup @bind-Value="request.Difficulty">
                    <Radio Value="@("简单")">简单</Radio>
                    <Radio Value="@("标准")">标准</Radio>
                    <Radio Value="@("困难")">困难</Radio>
                </RadioGroup>
            </FormItem>
            
            <FormItem Label="题目数量">
                <Slider @bind-Value="questionCountDouble" 
                        @bind-Value:after="OnQuestionCountChangedAsync"
                        Min="5.0" 
                        Max="20.0" 
                        Step="1.0" />
                <div style="text-align: center; margin-top: 8px;">
                    <Text Strong>@request.QuestionCount 道题</Text>
                </div>
            </FormItem>
            
            <FormItem Label="自定义要求">
                <TextArea @bind-Value="request.CustomRequirement" 
                          Placeholder="可以输入特殊要求，如：重点练习某个知识点、增加某种题型等（可选）"
                          Rows="3" />
            </FormItem>
            
            @if (!string.IsNullOrEmpty(previewContent))
            {
                <FormItem Label="预览信息">
                    <Alert Type="@AlertType.Info" 
                           Message="试卷预览" 
                           Description="@previewContent" />
                </FormItem>
            }
            
            <FormItem WrapperCol="new ColLayoutParam { Offset = 4, Span = 20 }">
                <Space>
                    <SpaceItem>
                        <Button Type="@ButtonType.Primary" 
                                HtmlType="submit" 
                                Loading="generating"
                                Disabled="!CanGenerate">
                            <Icon Type="thunderbolt" />
                            生成试卷
                        </Button>
                    </SpaceItem>
                    <SpaceItem>
                        <Button OnClick="ResetForm">
                            重置
                        </Button>
                    </SpaceItem>
                </Space>
            </FormItem>
        </Form>
    </Card>
    
    @if (generatedExam != null)
    {
        <Card Title="生成结果" Style="margin-top: 24px;">
            <Result Status="success" 
                    Title="试卷生成成功！" 
                    SubTitle="@($"已为 {selectedChild?.Name} 生成 {generatedExam.Type} 试卷")">
                <Space>
                    <SpaceItem>
                        <Button Type="@ButtonType.Primary" OnClick="ViewExam">
                            查看试卷
                        </Button>
                    </SpaceItem>
                    <SpaceItem>
                        <Button OnClick="PrintExam">
                            打印试卷
                        </Button>
                    </SpaceItem>
                    <SpaceItem>
                        <Button OnClick="GenerateAnother">
                            再生成一份
                        </Button>
                    </SpaceItem>
                </Space>
            </Result>
        </Card>
    }
</div>

@code {
    private ExamGenerationRequest request = new();
    private List<ChildProfile>? children;
    private ChildProfile? selectedChild;
    private ExamPaper? generatedExam;
    private bool generating = false;
    private string examTypeDescription = "";
    private string previewContent = "";
    private double questionCountDouble = 10.0;
    
    private Dictionary<int, string> sliderMarks = new()
    {
        { 5, "5" },
        { 10, "10" },
        { 15, "15" },
        { 20, "20" }
    };
    
    private bool CanGenerate => 
        request.ChildId > 0 && 
        !string.IsNullOrEmpty(request.ExamType) && 
        !generating;
    
    protected override async Task OnInitializedAsync()
    {
        await LoadChildren();
        // 初始化题目数量
        request.QuestionCount = (int)questionCountDouble;
        UpdateExamTypeDescription();
        UpdatePreview();
    }
    
    private async Task LoadChildren()
    {
        try
        {
            children = await LocalStorage.GetChildrenAsync();
            if (children.Any())
            {
                request.ChildId = children.First().Id;
                selectedChild = children.First();
            }
        }
        catch (Exception ex)
        {
            await LogService.LogErrorAsync($"加载孩子列表失败: {ex.Message}", "ExamGenerate");
        }
    }
    
    private void OnChildChanged()
    {
        selectedChild = children?.FirstOrDefault(c => c.Id == request.ChildId);
        UpdatePreview();
        StateHasChanged();
    }
    
    private Task OnExamTypeChangedAsync()
    {
        UpdateExamTypeDescription();
        UpdatePreview();
        StateHasChanged();
        return Task.CompletedTask;
    }
    
    private void UpdateExamTypeDescription()
    {
        examTypeDescription = request.ExamType switch
        {
            ExamTypes.MathApplication => "生成适合小学生的数学应用题，培养逻辑思维和计算能力",
            ExamTypes.ChinesePinyinToHanzi => "看拼音写汉字练习，提高汉字识别和书写能力",
            ExamTypes.ChineseHanziToPinyin => "看汉字写拼音练习，加强拼音基础",
            ExamTypes.ChineseEssayReading => "优秀作文阅读理解，提升语文理解和表达能力",
            ExamTypes.Comprehensive => "综合各科目知识点的练习题",
            _ => ""
        };
    }
    
    private void UpdatePreview()
    {
        if (selectedChild != null && !string.IsNullOrEmpty(request.ExamType))
        {
            previewContent = $"将为 {selectedChild.Name}（{selectedChild.Grade}年级 {selectedChild.Semester} {selectedChild.Stage}）生成 {request.QuestionCount} 道 {request.ExamType}，难度等级：{request.Difficulty}";
        }
        else
        {
            previewContent = "";
        }
    }
    
    private async Task GenerateExam()
    {
        if (!CanGenerate) return;
        
        try
        {
            generating = true;
            generatedExam = null;
            
            await LogService.LogInfoAsync($"开始生成试卷，类型: {request.ExamType}，孩子: {selectedChild?.Name}", "ExamGenerate");
            
            generatedExam = await ExamService.GenerateExamAsync(request);
            
            await LogService.LogInfoAsync($"试卷生成成功: {generatedExam.Title}", "ExamGenerate");
        }
        catch (Exception ex)
        {
            await LogService.LogErrorAsync($"生成试卷失败: {ex.Message}", "ExamGenerate");
            // TODO: 显示错误提示
        }
        finally
        {
            generating = false;
            StateHasChanged();
        }
    }
    
    private void ResetForm()
    {
        request = new ExamGenerationRequest();
        generatedExam = null;
        selectedChild = null;
        
        if (children?.Any() == true)
        {
            request.ChildId = children.First().Id;
            selectedChild = children.First();
        }
        
        UpdateExamTypeDescription();
        UpdatePreview();
        StateHasChanged();
    }
    
    private void ViewExam()
    {
        if (generatedExam != null)
        {
            Navigation.NavigateTo($"/exams/{generatedExam.Id}");
        }
    }
    
    private async Task PrintExam()
    {
        if (generatedExam != null)
        {
            // TODO: 实现打印功能
            await LogService.LogInfoAsync($"打印试卷: {generatedExam.Title}", "ExamGenerate");
        }
    }
    
    private void GenerateAnother()
    {
        generatedExam = null;
        StateHasChanged();
    }
    
    private void OnQuestionCountChanged(double value)
    {
        questionCountDouble = value;
        request.QuestionCount = (int)value;
        UpdatePreview();
        StateHasChanged();
    }
    
    private void OnQuestionCountChangedAsync()
    {
        request.QuestionCount = (int)questionCountDouble;
        UpdatePreview();
        StateHasChanged();
    }
} 